package common.security;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import common.security.service.UserService;

/**
 * 
 * 用于用户的业务类 获取权限
 */
public class MyUserDetailServiceImpl implements UserDetailsService {

	private UserService userService;


	protected final Log logger = LogFactory.getLog(getClass());

	protected final MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
	
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	// 登录验证
	@SuppressWarnings("deprecation")
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 根据用户名得到用户
		Set<GrantedAuthority> auths = new HashSet<GrantedAuthority>();
		common.rbac.po.User users = (common.rbac.po.User) this.userService.findUserAndAllAuthority(username, auths);
		if (null == users) {
			logger.debug("Query returned no results for user '" + username + "'");
			throw new UsernameNotFoundException(messages.getMessage("JdbcDaoImpl.notFound", new Object[] { username },
					"Username {0} not found"), username);
		}

		// 封装成spring security的user
		common.security.User userdetail = new common.security.User(users, auths);
		return userdetail;
	}

}
